package itqf.dao;


import itqf.dao.impl.ItemDao;
import itqf.entity.Item;
import itqf.entity.Product;
import itqf.utils.DruidUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * com.itqf.dao
 * 2020/9/17
 */
public class ItemDaoImpl implements ItemDao {
    QueryRunner qr = new QueryRunner(DruidUtils.getDateSource());
    @Override
    public int addItem(Item item) {
        String sql = "insert into item(o_id,p_id,i_count,i_num) values(?,?,?,?)";
        try {
            return qr.update(sql,item.getOid(),item.getPid(),item.getIcount(),item.getInum());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Item> findItemByOid(String oid) {
        String sql = "select i_id as iid,o_id as oid,i.p_id as pid,i_count as icount,i_num as inum,p_name as pname," +
                "p_time as ptime,p_image as pimage,p_price as pprice,p_state as pstate," +
                "p_info as pinfo from item i inner join product p on i.p_id=p.p_id where o_id=?";
        try {
            List<Map<String, Object>> list = qr.query(sql, new MapListHandler(), oid);
            List<Item> itemlist = new ArrayList<>();
            for (Map<String, Object> map : list) {
                Item item = new Item();
                Product product = new Product();
                BeanUtils.populate(item,map);
                BeanUtils.populate(product,map);
                item.setProduct(product);
                itemlist.add(item);
            }
            return itemlist;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
